package org.zzq.my12306.frameworks.starter.distributedid.core.snowflake;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.zzq.my12306.frameworks.starter.distributedid.toolkit.SnowflakeIdUtil;

/**
 * 雪花算法生成 ID 模版类
 */
@Slf4j
public abstract class AbstractWorkIdChooseTemplate {
    /**
     * 是否使用 SystemClock 读取当前时间戳
     */
    @Value("${framework.distributed.id.snowflake.is-use-system-clock:false}")
    private boolean isUseSystemClock;

    /**
     * 根据自定义策略获取 workId 生成器
     */
    protected abstract WorkIdWrapper chooseWorkId();

    /**
     * 选择 workId 并初始化雪花
     */
    public void chooseAndInit() {
        // 模版方法模式：通过抽象方法获取 workId 包装器创建雪花算法
        WorkIdWrapper workIdWrapper = chooseWorkId();
        long workId = workIdWrapper.getWorkId();
        Long dataCenterId = workIdWrapper.getDataCenterId();
        Snowflake snowflake = new Snowflake(workId, dataCenterId, isUseSystemClock);
        log.info("snowflake type: {}, workId: {}, dataCenterId: {}", this.getClass().getSimpleName(), workId, dataCenterId);
        SnowflakeIdUtil.initSnowflake(snowflake);
    }
}
